package com.db;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 * Created by 付晨 on 2017/3/4.
 */
public class DBSerives {
    public static void delete(Object sender) {

        commonlyDB(sender,State.delete);
    }

    public static void add(Object sender) {

        commonlyDB(sender,State.adds);
    }

    public static void update(Object sender) {
        commonlyDB(sender,State.update);
    }

    public static Object load(Object sender, Integer id) {
        Session session = HibernateSessionFactory.getSession();
        Object object = session.get(sender.getClass(), id);
        HibernateSessionFactory.closeSession();
        return object;
    }

    private static void commonlyDB(Object sender,State state) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            switch (state){
                case adds:
                    session.save(sender);
                    break;
                case delete:
                    session.delete(sender);
                    break;
                case update:
                    session.update(sender);
                    break;
            }
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            HibernateSessionFactory.closeSession();
        }
    }

    enum State {
        adds, update, delete
    }
}
